<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8' />
  <title>mbview - vector</title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
  <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.3.1/mapbox-gl.js'></script>
  <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.3.1/mapbox-gl.css' rel='stylesheet' />
  <link href='https://www.mapbox.com/base/latest/base.css' rel='stylesheet' />
  <style>
    body { margin:0; padding:0; }
    #map { position:absolute; top:0; bottom:0; width:100%; }
    .mbview_popup {
      color: #333;
      display: table;
      font-family: "Open Sans", sans-serif;
      font-size: 10px;
    }

    .mbview_feature:not(:last-child) {
      border-bottom: 1px solid #ccc;
    }

    .mbview_layer:before {
      content: '#';
    }

    .mbview_layer {
      display: block;
      font-weight: bold;
    }

    .mbview_property {
      display: table-row;
    }

    .mbview_property-value {
      display: table-cell;

    }

    .mbview_property-name {
      display: table-cell;
      padding-right: 10px;
    }
  </style>
</head>
<body>

<%- include('menu') %>

<div id='map'></div>

<script>

var center = [<%= center %>];
center = [center[0], center[1]];

mapboxgl.accessToken = '<%= accessToken %>';
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/<%= basemap %>-v9',
  center: center,
  zoom: <%= zoom %>,
  hash: true,
  maxZoom: 30
});

var layers = {
  pts: [],
  lines: [],
  polygons: []
}

var lightColors = [
  'FC49A3', // pink
  'CC66FF', // purple-ish
  '66CCFF', // sky blue
  '66FFCC', // teal
  '00FF00', // lime green
  'FFCC66', // light orange
  'FF6666', // salmon
  'FF0000', // red
  'FF8000', // orange
  'FFFF66', // yellow
  '00FFFF'  // turquoise
];

function randomColor(colors) {
  var randomNumber = parseInt(Math.random() * colors.length);
  return colors[randomNumber];
}

map.on('load', function () {
  <% Object.keys(sources).forEach(function (sid) { %>

    map.addSource('<%= sid %>', {
      type: 'vector',
      tiles: [
        'http://<%= host %>:<%= port %>/<%= sid %>/{z}/{x}/{y}.pbf'
      ],
      maxzoom: <%= sources[sid].maxzoom %>
    });

    <%- include('layers', {sid: sid}) %>

  <% }); %>
});


function displayValue(value,propName) {
  if (propName=== '@timestamp'){
    return value.toString() + "<br>[ " + (new Date(value*1000)).toISOString() + " ]";
  }
  if (typeof value === 'undefined' || value === null) return value;
  if (typeof value === 'object' ||
      typeof value === 'number' ||
      typeof value === 'string') return value.toString();
  return value;
}

function renderProperty(propertyName, property) {
  return '<div class="mbview_property">' +
    '<div class="mbview_property-name">' + propertyName + '</div>' +
    '<div class="mbview_property-value">' + displayValue(property,propertyName) + '</div>' +
    '</div>';
}

function renderLayer(layerId) {
  return '<div class="mbview_layer">' + layerId + '</div>';
}

function renderProperties(feature) {
  var sourceProperty = renderLayer(feature.layer['source-layer'] || feature.layer.source);
  var idProperty = renderProperty('$id', feature.id);
  var typeProperty = renderProperty('$type', feature.geometry.type);
  var properties = Object.keys(feature.properties).map(function (propertyName) {
    return renderProperty(propertyName, feature.properties[propertyName]);
  });
  return (feature.id ? [sourceProperty, idProperty, typeProperty]
    : [sourceProperty, typeProperty]).concat(properties).join('');
}

function renderFeatures(features) {
  return features.map(function (ft) {
    return '<div class="mbview_feature">' + renderProperties(ft) + '</div>';
  }).join('');
}

function renderPopup(features) {
  return '<div class="mbview_popup">' + renderFeatures(features) + '</div>';
}

var popup = new mapboxgl.Popup({
  closeButton: false,
  closeOnClick: false
});

var wantPopup = false;

map.on('mousemove', function (e) {
  // set a bbox around the pointer
  var selectThreshold = 3;
  var queryBox = [
    [
      e.point.x - selectThreshold,
      e.point.y + selectThreshold
    ], // bottom left (SW)
    [
      e.point.x + selectThreshold,
      e.point.y - selectThreshold
    ] // top right (NE)
  ];

  var features = map.queryRenderedFeatures(queryBox, {
    layers: layers.polygons.concat(layers.lines.concat(layers.pts))
  }) || [];
  map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';

  if (!features.length || !wantPopup) {
    popup.remove();
  } else {
    popup.setLngLat(e.lngLat)
      .setHTML(renderPopup(features))
      .addTo(map);
  }
});
</script>

</body>
</html>
